import { useCssVar, useDark, useStorage, useToggle } from '@vueuse/core';
import { defineStore } from 'pinia';
import { computed, watch } from 'vue';

// 预设主题颜色
export const THEME_COLORS = {
  blue: {
    name: '蓝色',
    primary: '#1890ff',
  },
  green: {
    name: '绿色',
    primary: '#52c41a',
  },
  purple: {
    name: '紫色',
    primary: '#722ed1',
  },
  red: {
    name: '红色',
    primary: '#f5222d',
  },
  orange: {
    name: '橙色',
    primary: '#fa8c16',
  },
  cyan: {
    name: '青色',
    primary: '#13c2c2',
  },
};

export const useThemeStore = defineStore('theme', () => {
  // 使用 VueUse 的 useDark，自动处理暗黑模式切换和持久化
  const isDark = useDark({
    selector: 'html',
    attribute: 'class',
    valueDark: 'dark',
    valueLight: '',
    storageKey: 'app-theme',
    storage: localStorage,
  });

  // 使用 useStorage 持久化主题颜色选择
  const currentThemeColor = useStorage<keyof typeof THEME_COLORS>('app-theme-color', 'blue');

  // 使用 useCssVar 管理CSS变量
  const primaryColor = useCssVar('--el-color-primary');
  const primaryColorLight3 = useCssVar('--el-color-primary-light-3');
  const primaryColorDark2 = useCssVar('--el-color-primary-dark-2');

  // 切换主题的函数
  const toggleDark = useToggle(isDark);

  // 为了保持向后兼容性，提供原有的 API
  const isDarkMode = computed(() => isDark.value);

  // 切换主题
  const toggleTheme = () => {
    toggleDark();
  };

  // 设置主题
  const setTheme = (theme: 'light' | 'dark') => {
    isDark.value = theme === 'dark';
  };

  // 设置主题颜色
  const setThemeColor = (colorKey: keyof typeof THEME_COLORS) => {
    currentThemeColor.value = colorKey;
    applyThemeColor();
  };

  // 颜色转换工具函数
  const hex2rgb = (hex: string) => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result
      ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16),
        }
      : null;
  };

  // 生成颜色变体
  const generateColorVariants = (baseColor: string) => {
    const rgb = hex2rgb(baseColor);
    if (!rgb) return {};

    const variants: Record<string, string> = {};

    // 生成浅色变体 (混合白色)
    for (let i = 1; i <= 9; i++) {
      const ratio = i / 10;
      const r = Math.round(rgb.r + (255 - rgb.r) * ratio);
      const g = Math.round(rgb.g + (255 - rgb.g) * ratio);
      const b = Math.round(rgb.b + (255 - rgb.b) * ratio);
      variants[`light-${i}`] = `rgb(${r}, ${g}, ${b})`;
    }

    // 生成深色变体 (混合黑色)
    for (let i = 1; i <= 2; i++) {
      const ratio = i * 0.1;
      const r = Math.round(rgb.r * (1 - ratio));
      const g = Math.round(rgb.g * (1 - ratio));
      const b = Math.round(rgb.b * (1 - ratio));
      variants[`dark-${i}`] = `rgb(${r}, ${g}, ${b})`;
    }

    return variants;
  };

  // 应用主题颜色到CSS变量
  const applyThemeColor = () => {
    const colors = THEME_COLORS[currentThemeColor.value];
    const variants = generateColorVariants(colors.primary);

    // 设置主色调
    primaryColor.value = colors.primary;

    // 设置常用变体
    if (variants['light-3']) {
      primaryColorLight3.value = variants['light-3'];
    }
    if (variants['dark-2']) {
      primaryColorDark2.value = variants['dark-2'];
    }

    // 使用 useCssVar 设置所有变体
    Object.entries(variants).forEach(([key, value]) => {
      const cssVar = useCssVar(`--el-color-primary-${key}`);
      cssVar.value = value;
    });
  };

  // 获取Ant Design主题配置
  const getAntdThemeConfig = computed(() => {
    const colors = THEME_COLORS[currentThemeColor.value];
    return {
      token: {
        colorPrimary: colors.primary,
      },
    };
  });

  // 初始化主题（VueUse 会自动处理，但保留接口兼容性）
  const initTheme = () => {
    // VueUse 的 useDark 会自动初始化，这里可以添加额外的初始化逻辑
    applyTheme();
    applyThemeColor();
  };

  // 应用主题到 document（添加额外的属性和类名）
  const applyTheme = () => {
    if (typeof window !== 'undefined' && window.document) {
      if (isDark.value) {
        // 添加额外的属性和类名以确保兼容性
        document.documentElement.setAttribute('data-theme', 'dark');
        document.documentElement.classList.add('dark-theme');
      } else {
        document.documentElement.setAttribute('data-theme', 'light');
        document.documentElement.classList.remove('dark-theme');
      }
    }
  };

  // 监听主题变化，应用额外的样式
  watch(
    isDark,
    () => {
      applyTheme();
    },
    { immediate: true },
  );

  // 监听主题颜色变化，自动应用
  watch(
    currentThemeColor,
    () => {
      applyThemeColor();
    },
    { immediate: true },
  );

  // 监听系统主题变化（VueUse 已经自动处理，保留接口兼容性）
  const watchSystemTheme = () => {
    // VueUse 的 useDark 已经自动监听系统主题变化
    // 这里可以添加额外的逻辑
  };

  return {
    isDark,
    isDarkMode,
    toggleDark,
    initTheme,
    toggleTheme,
    setTheme,
    applyTheme,
    watchSystemTheme,
    currentThemeColor,
    setThemeColor,
    getAntdThemeConfig,
  };
});
